// 将文章列表拆分成一个单独的组件 (注意: 不要忘了在首页组件中调用该组件)
// src/pages/home/widgets/article/index.tsx
import styles from "@styles/home.module.scss";
import {useEffect, useRef, useState} from "react";
import classNames from "classnames";
import {useTypedDispatch, useTypedSelector} from "@store/index";
import {saveArticles, selectArticles} from "@store/slices/articleSlice";
import {useLazyRequestArticlesQuery} from "@store/apiSlice/ArticleApiSlice";
import {InfiniteScroll} from "antd-mobile";
import {useOutletContext} from "react-router-dom";
import {OutletContextType} from "@shared/layout";
import Doctors from "@pages/home/widgets/doctors";

export default function Article() {
    // 用于记录用户选择的文章类型
    const [type, setType] = useState<ArticleType>("recommend");
    //根据文章类型获取文章状态
    // 根据文章类型获取文章状态
    const { current, pageSize, articles, hasMore } = useTypedSelector(selectArticles(type));
    // 用于发送请求获取文章列表
    const [requestArticles] = useLazyRequestArticlesQuery();
    //获取dispatch 方法
    const dispatch = useTypedDispatch()
    //用于加载文章列表
    const loadMore = () =>{
        // 注意 InfiniteScroll 组件要求 loadMore 函数必须返回请求对应的 Promise 对象
        // 发送请求获取文章列表
        return requestArticles({type,current,pageSize})
            .unwrap()
            .then(({data:{pageTotal,rows}})=>{
                //布尔类型，表示是否还有更多数据
                const hasMore = current < pageTotal;
                //保存文章列表
                dispatch(
                    saveArticles({
                        //文章分类
                        type,
                        //更新页码
                        current: hasMore ? current +1 : current,
                        //更新是否还有更多数据的状态
                        hasMore,
                        //保存文章列表
                        articles: rows,
                        //更新页码
                        pageSize: 10
                    })
                )
            })
    }
     //切换文章类型
    const requestArticle = (type:ArticleType) =>{
        setType(type)
        loadMore()
    }
    // 获取内容区域的滚动距离
    const { scrollTop } = useOutletContext<OutletContextType>();
    // 用于记录文章分类区域的是否吸顶状态
    const [fixed, setFixed] = useState(false);
    // 用于记录文章分类区域与页面顶部的距离
    const offsetTop = useRef(0);
    //监控内容区域的滚动
    useEffect(()=>{
        //如果内容区域的滚动距离大于文章分类区域与页面顶部的距离
        //设置吸顶,否则取消吸顶

        setFixed(scrollTop > offsetTop.current)
    },[scrollTop])
    return (
        <>
            {fixed ? <div className={styles.filler}></div> : null}
            <div ref={(element) => {
                if (element !== null && !fixed) {
                    offsetTop.current = element.offsetTop;
                }
            }}
                 className={classNames(styles.category, { [styles.fixed]: fixed })}>
              <span
                  onClick={() => requestArticle("like")}
                  className={classNames({ [styles.active]: type === "like" })}
              >
        关注
      </span>
                <span
                    onClick={() => requestArticle("recommend")}
                    className={classNames({ [styles.active]: type === "recommend" })}
                >
        推荐
      </span>
                <span
                    onClick={() => requestArticle("fatReduction")}
                    className={classNames({ [styles.active]: type === "fatReduction" })}
                >
        减脂
      </span>
                <span
                    onClick={() => requestArticle("food")}
                    className={classNames({ [styles.active]: type === "food" })}
                >
        饮食
      </span>
            </div>
            {(type === "like") &&  <div className={styles.focus}>
                <Doctors></Doctors>
            </div>}

            <div className={styles.article}>
                {articles.map((article) => (
                    <div className={styles.item} key={article.id}>
                        <div className={styles.meta}>
                            <div className={styles.left}>
                                <img
                                    src={article.creatorAvatar}
                                    alt=""
                                    className={styles.avatar}
                                />
                                <div className={styles.info}>
                                    <span>{article.creatorName}</span>
                                    <i>
                                        {article.creatorHospatalName}&nbsp;{article.creatorDep}
                                        &nbsp;{article.creatorTitles}
                                    </i>
                                </div>
                            </div>
                            <button className={styles.attention}>
                                {article.likeFlag === 0 ? "+ 关注" : "已关注"}
                            </button>
                        </div>
                        <h4 className={styles.title}>{article.title}</h4>
                        <div className={styles.tag}># {article.topic}</div>
                        <div className={styles.content}>
                            {article.content.replace(/<[^>]+>/g, "")}
                        </div>
                        <div className={styles.container}>
                            {article.coverUrl.map((url, index) => (
                                <img key={index} src={url} alt="" />
                            ))}
                        </div>
                        <div className={styles.footer}>
                            <span>{article.collectionNumber} 收藏</span>
                            <span>{article.commentNumber} 评论</span>
                        </div>
                    </div>
                ))}
            </div>
            <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
        </>
    );
}